package com.mall.common;

import cn.hutool.core.util.DesensitizedUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.mall.note.Sensitize;
import org.apache.commons.lang3.ObjectUtils;

import java.io.IOException;

/**
 * @Description 自定义的数据脱敏序列化器
 * @ClassName SensitizeSerializer
 * @Author cxx
 * @Date 2023/4/25 19:39
 * @Version 1.0
 */

public class SensitizeSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private DesensitizedUtil.DesensitizedType type;

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        Sensitize sensitize = beanProperty.getAnnotation(Sensitize.class);
        if (ObjectUtils.isNotEmpty(sensitize)) {
            this.type=sensitize.type();
            return this;
        }

        return serializerProvider.findValueSerializer(beanProperty.getType(),beanProperty);
    }

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(DesensitizedUtil.desensitized(s, type));

    }

}

